import yaml

from django.forms import Widget
from django.utils.safestring import mark_safe
from django.forms.widgets import flatatt

class AttributesInput(Widget):
	"""A widget that displays yaml Key Value Pairs
	as a list of text input box pairs
	
	http://www.huyng.com/posts/django-custom-form-widget-for-dictionary-and-tuple-key-value-pairs/
	"""

	def __init__(self, *args, **kwargs):
		"""A widget that displays yaml Key Value Pairs
		as a list of text input box pairs

		kwargs:
		key_attrs -- html attributes applied to the 1st input box pairs
		val_attrs -- html attributes applied to the 2nd input box pairs

		"""
		self.key_attrs = {}
		self.val_attrs = {}
		if "key_attrs" in kwargs:
			self.key_attrs = kwargs.pop("key_attrs")
		if "val_attrs" in kwargs:
			self.val_attrs = kwargs.pop("val_attrs")

#		self.inputs_count = len(self.key_attrs) + 1
		Widget.__init__(self, *args, **kwargs)

	def render(self, name, value, attrs=None):
		"""Renders this widget into an html string

		args:
		name  (str)  -- name of the field
		value (str)  -- a yaml string automatically passed in by django
		attrs (dict) -- automatically passed in by django (unused in this function)
		"""
		if value is None or value.strip() is '':
			data = {}
		else:
			data = yaml.load(value)

		output = ''
		key_attrs = flatatt(self.key_attrs)
		val_attrs = flatatt(self.val_attrs)
		if value and len(value) > 0:
			for key in sorted(data):
				ctx = {
						'key': key,
						'value': data[key],
						'fieldname': name,
						'key_attrs': key_attrs,
						'val_attrs': val_attrs,
				}
				output += '<input type="text" name="attr_key" value="%(key)s" %(key_attrs)s>: <input type="text" name="attr_value" value="%(value)s" %(val_attrs)s><br />' % ctx
		# empty input boxes for new attributes
		output += '<input type="text" name="attr_key" %s>: <input type="text" name="attr_value" %s>' % (key_attrs, val_attrs)

		output += ("""
<script type="text/javascript">
</script>""")

		return mark_safe(output)

	def value_from_datadict(self, data, files, name):
		"""
		Returns the yaml representation of the key-value pairs
		sent in the POST parameters

		args:
		data  (dict)  -- request.POST or request.GET parameters
		files (list)  -- request.FILES
		name  (str)   -- the name of the field associated with this widget

		"""
		if data.has_key('attr_key') and data.has_key('attr_value'):
			keys = data.getlist('attr_key')
			values = data.getlist('attr_value')
			data = {}
			for key, value in zip(keys, values):
				if len(key) > 0:
					data[key] = value
			return yaml.safe_dump(data)
		else:
			return ''

